package cn.lopr.im.android.mvp.view.fragments;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.lopr.im.android.R;
import cn.lopr.im.android.bean.User;
import cn.lopr.im.android.common.Constant;
import cn.lopr.im.android.common.widget.SideBar;
import cn.lopr.im.android.databinding.FragmentContactBinding;
import cn.lopr.im.android.db.entity.Message;
import cn.lopr.im.android.db.service.MessageDaoService;
import cn.lopr.im.android.mvp.contact.IContactContact;
import cn.lopr.im.android.mvp.presenter.ContactPresenterImpl;
import cn.lopr.im.android.mvp.view.activities.AddFriendActivity;
import cn.lopr.im.android.mvp.view.activities.ChatActivity;
import cn.lopr.im.android.mvp.view.activities.MainActivity;
import cn.lopr.im.android.mvp.view.adapters.SortRecyclerViewAdapter;
import cn.lopr.im.android.mvp.view.adapters.base.CharacterParser;
import cn.lopr.im.android.mvp.view.adapters.base.PinyinComparator;


/**
 * 聊天列表
 *
 * @author shuangyang7
 * @date 2020/12/30 13:36
 */
public class ContactFragment extends Fragment implements IContactContact.IContactView {

    private static final String ARG_COLUMN_COUNT = "column-count";
    private ContactReceiver contactReceiver;
    private FragmentContactBinding binding;

    private ContactPresenterImpl contactPresenterImpl;
    private CharacterParser characterParser;
    private PinyinComparator pinyinComparator;

    private SortRecyclerViewAdapter sortRecyclerViewAdapter;
    private RecyclerView recyclerView;
    private SideBar sideBar;
    private EditText filterEdit;
    private TextView tvMsgNum;
    private LinearLayout llNewFriends;
    private SwipeRefreshLayout swipeRefresh;

    private List<User> users;

    @SuppressWarnings("unused")
    public static ContactFragment newInstance(int columnCount) {
        ContactFragment fragment = new ContactFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contact, container, false);
        this.binding = FragmentContactBinding.inflate(inflater);

        initWidget(view);
        initData();
        return view;
    }

    private void initWidget(View view) {
        this.sideBar = (SideBar) view.findViewById(R.id.sidrbar);
        this.recyclerView = (RecyclerView) view.findViewById(R.id.list);
        this.filterEdit = (EditText) view.findViewById(R.id.et_search_content);
        this.tvMsgNum = (TextView) view.findViewById(R.id.tv_msg_num);
        this.swipeRefresh = view.findViewById(R.id.swipeRefresh);
        this.llNewFriends = view.findViewById(R.id.ll_newFriends);
        this.sideBar.setTextView(binding.dialog);
        this.llNewFriends.setOnClickListener(v -> {
            Intent intent = new Intent(this.getContext(), AddFriendActivity.class);
            intent.putExtra("action", "apply");
            getActivity().startActivity(intent);
        });
        this.sideBar.setOnItemSelectListener(s -> {
            //该字母首次出现的位置
            int position = sortRecyclerViewAdapter.getPositionForSection(s.charAt(0));
            if (position != -1) {
                recyclerView.scrollToPosition(position);
            }
        });

        this.swipeRefresh.setOnRefreshListener(() -> {
            contactPresenterImpl.getFriend();
            this.swipeRefresh.setRefreshing(false);
        });

        this.filterEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Log.i("filter", "beforeTextChanged: " + charSequence);
                filterData(charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @SuppressLint("SetTextI18n")
    private void initData() {

        this.users = new ArrayList<>();
        this.characterParser = CharacterParser.getInstance();
        this.pinyinComparator = new PinyinComparator();
        this.contactPresenterImpl = new ContactPresenterImpl(this, this);

        doRegisterReceiver();
    }

    @Override
    public void getFriendSuccess(List<User> users) {

        this.users = users;

        Context context = this.getContext();

        this.sortRecyclerViewAdapter = new SortRecyclerViewAdapter(context, this.users);

        this.recyclerView.setAdapter(this.sortRecyclerViewAdapter);

        this.sortRecyclerViewAdapter.notifyDataSetChanged();

        this.sortRecyclerViewAdapter.onRecyclerViewItemClickListener(new SortRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int section) {
                Log.i("sortRecyclerViewAdapter", "onItemClick: " + view + " : " + section);
                Intent intent = new Intent(getActivity(), ChatActivity.class);
                intent.putExtra("friend", users.get(section));
                getActivity().startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int section) {
                Log.i("sortRecyclerViewAdapter", "onItemLongClick: " + view + " : " + section);
            }
        });
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr 过滤字符
     */
    private void filterData(String filterStr) {
        List<User> filterDataList = new ArrayList<>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDataList = this.users;

        } else {
            filterDataList.clear();
            for (User user : this.users) {
                String name = user.getNickname();
                if (name.contains(filterStr) || characterParser.getSelling(name).startsWith(filterStr)) {
                    filterDataList.add(user);
                }
            }

        }

        Collections.sort(filterDataList, pinyinComparator);
        this.sortRecyclerViewAdapter.add(filterDataList);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onResume() {
        super.onResume();
        if (this.contactPresenterImpl != null) {
            this.contactPresenterImpl.getFriend();
        }
        List<Message> messageByType = MessageDaoService.getMessageByType(MainActivity.user.getPhone(),
                Constant.MessageType.SEND_ADD.getCode() + "");

        if (messageByType.size() == 0) {
            tvMsgNum.setVisibility(View.GONE);
        } else {
            tvMsgNum.setText(messageByType.size() + "");
        }
    }


    private void doRegisterReceiver() {
        contactReceiver = new ContactReceiver();
        IntentFilter filter = new IntentFilter("cn.lopr.im.android.servicecallback.content.add");
        FragmentActivity fragmentActivity = getActivity();
        fragmentActivity.registerReceiver(contactReceiver, filter);
    }

    public class ContactReceiver extends BroadcastReceiver {

        @SuppressLint("SetTextI18n")
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent == null) {
                return;
            }
            Log.e("ContactReceive", "onReceive: ");

            List<Message> messageByType = MessageDaoService.getMessageByType(MainActivity.user.getPhone(),
                    Constant.MessageType.SEND_ADD.getCode() + "");

            if (messageByType.size() == 0) {
                tvMsgNum.setVisibility(View.GONE);
            } else {
                tvMsgNum.setVisibility(View.VISIBLE);
                tvMsgNum.setText(messageByType.size() + "");
            }

        }
    }
}